import file_manager
import model

teacher_name = ''


# 输入数据并创建一个Student object(不含学号)
def __enter_stu():
    stu_name = input('please enter student name:')
    while True:
        try:
            stu_age = int(input('please enter student age:'))
        except ValueError:
            print('invalid input')
        else:
            break
    while True:
        stu_sex = input('please enter student sex(0/1):')
        if stu_sex != '0' and stu_sex != '1':
            print('you should enter 0 or 1!')
        else:
            break
    while True:
        try:
            stu_tel = int(input('please enter student phone number:'))
        except ValueError:
            print('invalid input')
        else:
            break
    return model.Student(stu_name, stu_age, stu_sex, stu_tel)


# 通过id查找学生，存在返回True
def __find_stu(stu_id):
    teacher_json = file_manager.read_json(teacher_name + '.json', {'all_student': [], 'num': 0})
    for stu in teacher_json['all_student']:
        if stu_id == stu['id']:
            return True
    else:
        return False


def add_stu():
    while True:
        # 得到一个Student object
        stu = __enter_stu()
        # 将Student object添加到对应老师的json中
        # 1.读出teacher_name.json到teacher_json
        teacher_json = file_manager.read_json(teacher_name + '.json', {'all_student': [], 'num': 0})
        # 2.将学生信息放入teacher_json
        teacher_json['num'] += 1
        stu.__dict__['id'] = 'stu_' + str(teacher_json['num']).zfill(4)
        teacher_json['all_student'].append(stu.__dict__)
        # 3.将teacher_json存储到teacher_name.json文件中
        file_manager.write_json(teacher_name + '.json', teacher_json)
        print('Add complete!')
        # ==============================================================
        # continue or return
        print('continue(enter 1)')
        print('return(enter others)')
        if input('your choice:') != '1':
            break


def show_stu():
    teacher_json = file_manager.read_json(teacher_name + '.json', {'all_student': [], 'num': 0})
    all_student = teacher_json['all_student']
    if teacher_json['num'] != 0:
        print('teacher {} has {} students:'.format(teacher_name, teacher_json['num']))
        for stu in teacher_json['all_student']:
            if stu['name'] != '':
                print(stu)
    else:
        print('teacher {} has not added a student'.format(teacher_name))


# 删除学生，使指定学号的学生对象的age置0，id保留，其它所有属性置空
def __del_stu(stu_id):
    teacher_json = file_manager.read_json(teacher_name + '.json')
    index = int(stu_id.rsplit('_')[1]) - 1
    teacher_json['all_student'][index] = {'name': '', 'age': 0, 'sex': '', 'tel': '', 'id': stu_id}
    file_manager.write_json(teacher_name + '.json', teacher_json)


# 删除学生
def del_stu():
    while True:
        stu_id = input('enter id to delete:')
        if __find_stu(stu_id):
            __del_stu(stu_id)
            teacher_json = file_manager.read_json(teacher_name + '.json')
            teacher_json['num'] -= 1
            file_manager.write_json(teacher_name + '.json', teacher_json)
            print('continue(enter 1)')
            print('return(enter others)')
            if input('your choice:') != '1':
                break
        else:
            print('student not exist!')


def mod_stu_info():
    while True:
        stu_id = input('enter id to modify info:')
        if __find_stu(stu_id):
            teacher_json = file_manager.read_json(teacher_name + '.json')
            stu = __enter_stu()
            stu.id = stu_id
            __del_stu(stu_id)
            index = int(stu_id.rsplit('_')[1]) - 1
            teacher_json['all_student'][index] = stu.__dict__
            file_manager.write_json(teacher_name + '.json', teacher_json)
            print('continue(enter 1)')
            print('return(enter others)')
            if input('your choice:') != '1':
                break
        else:
            print('student not exist!')


def show_page():
    content = file_manager.read_file('student_manager.txt')

    while True:
        print(content % teacher_name)
        choice = input('please enter your choice(1-5):')
        if choice == '1':
            add_stu()
        elif choice == '2':
            show_stu()
        elif choice == '3':
            mod_stu_info()
        elif choice == '4':
            del_stu()
        elif choice == '5':
            return
        else:
            print('invalid input!')

# del __get_stu
